import { _decorator, CameraComponent, Component, Node, view, View } from 'cc';
import { RenderItem, RenderItemRenderState } from './RenderItem';
const { ccclass, property } = _decorator;


/**
 * 2D对象渲染管理
 */
@ccclass('RenderMananger2D')
export class RenderMananger2D extends Component {

    private static _list: RenderItem[] = []
    public static add(renderItem_: RenderItem) {
        RenderMananger2D._list.push(renderItem_)
    }
    public static remove(renderItem_: RenderItem) {
        const itemIndex_n = RenderMananger2D._list.indexOf(renderItem_)
        RenderMananger2D._list.splice(itemIndex_n, 1)

        console.log(RenderMananger2D._list)
    }
    public static clear() {  
        RenderMananger2D._list = []
    }

    @property({
        type: Node,
        tooltip: "相机节点"
    })
    cameraNode: Node = null


    private _camearVisibleW_n = view.getVisibleSize().width / 2
    private _camearVisibleH_n = view.getVisibleSize().height / 2


    start() {

    }

    update(deltaTime_n_: number) {
       this.intervalupdate(deltaTime_n_)
    }

    // 间隔执行
    private _timeInterval_n: number = 0.5
    private _timeIntervalCache_n: number = 0
    private intervalupdate(deltaTime_n_: number) {
        this._timeIntervalCache_n -= deltaTime_n_
        if (this._timeIntervalCache_n <= 0) {
            this._timeIntervalCache_n = this._timeInterval_n
            this.changeItemState()
        }
    }
    
    /**
     * 改变元素渲染状态
     */
    private changeItemState() {
        for (let index_n = 0; index_n < RenderMananger2D._list.length; index_n++) {
            const item_com = RenderMananger2D._list[index_n]
            const itemHalfWH_size = item_com.getVisibleHalfWH()
            const item_nd = item_com.node
            const subX_n = Math.abs(this.cameraNode.worldPosition.x - (item_nd.worldPosition.x + itemHalfWH_size.width))
            const subY_n = Math.abs(this.cameraNode.worldPosition.y - (item_nd.worldPosition.y + itemHalfWH_size.height)) 

            if (subX_n < this._camearVisibleW_n && subY_n < this._camearVisibleH_n ) {
                item_com.setState(RenderItemRenderState.OPACITY)
            } else {
                item_com.setState(RenderItemRenderState.TRANSPARENT)
            }
        }
    }
}